package com.ego.service.impl;

import com.ego.dubbo.service.ContentDubboService;
import com.ego.pojo.Content;
import com.ego.pojo.EasyUIDatagrid;
import com.ego.pojo.EgoResult;
import com.ego.sender.RabbitMQSender;
import com.ego.service.ContentService;
import com.ego.utils.IDUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ContentServiceImpl implements ContentService {

    @Autowired
    private RabbitMQSender rabbitMQSender;

    @Value("${ego.rabbitmq.exchange.direct}")
    private String directExchange;

    @Value("${ego.rabbitmq.queue.content-insert}")
    private String contentInsertQueue;

    @Value(("${ego.rabbitmq.queue.content-update}"))
    private String contentUpdateQueue;

    @Value(("${ego.rabbitmq.queue.content-delete}"))
    private String contentDeleteQueue;

    @DubboReference
    private ContentDubboService contentDubboService;

    @Override
    public EasyUIDatagrid selectContentByPage(Long categoryId, int pageNum, int pageSize) {
        List<Content> contents = contentDubboService.selectContentByPage(categoryId, pageNum, pageSize);
        long total = contentDubboService.selectTotal(categoryId);
        EasyUIDatagrid easyUIDatagrid = new EasyUIDatagrid(contents, total);
        return easyUIDatagrid;
    }

    @Override
    public EgoResult saveContent(Content content) {
        content.setId(IDUtils.genItemId());
        Date now = new Date();
        content.setCreated(now);
        content.setUpdated(now);
        int result = contentDubboService.saveContent(content);
        if (result == 1) {
            rabbitMQSender.sendDirect(directExchange,contentInsertQueue,content);
            return EgoResult.ok();
        }
        return EgoResult.error("新增内容失败");
    }

    @Override
    public EgoResult updateContent(Content content) {
        content.setUpdated(new Date());
        int result = contentDubboService.updateContent(content);
        if (result == 1) {
            rabbitMQSender.sendDirect(directExchange, contentUpdateQueue, content);
            return EgoResult.ok();
        }
        return EgoResult.error("修改内容失败");
    }

    @Override
    public EgoResult deleteContent(Long[] ids) {
        int result = contentDubboService.deleteContentByIds(ids);
        if (result == 1) {
            rabbitMQSender.sendDirect(directExchange, contentDeleteQueue, ids);
            return EgoResult.ok();
        }
        return EgoResult.error("删除内容失败");
    }
}
